<?php
	
	class CodexecsController extends AppController {
		
		var $name = 'Codexecs';
		var $helpers = array('Text', 'Csv');
		var $paginate = array('limit' => 50);
		
		//var $uses = array('Codexec','Codetail');
		function admin_index() {
			$this->Codexec->recursive = 0;
			$this->set('codexecs', $this->paginate());
		}
		
		function admin_view($id = null) {
			if (!$id) {
				$this->Session->setFlash(__('Invalid codexec', true));
				$this->redirect(array('action' => 'index'));
			}
			$this->set('codexec', $this->Codexec->read(null, $id));
		}
		
		function sharequotes($sharecode, $date=null) {
			if (empty($date)) {
				$url = "http://download.finance.yahoo.com/d/quotes.csv?s=" . $sharecode . "&f=sl1d1t1c&e=.csv";
				$filesize = 2000;
				$handle = @fopen($url, "r");
				if ($handle) {
					$raw_quote_data = @fread($handle, $filesize);
					fclose($handle);
					$quote_array = explode("\n", $raw_quote_data);
					//pr($quote_array);
					//array_shift($quote_array);
					array_pop($quote_array);
					
					$quote = explode(",", $quote_array['0']);
					return $quote['1'];
				}
				else
                return false;
				}else {
				$dates = explode("-", $date);
				$url = "http://ichart.finance.yahoo.com/table.csv?s=" . $sharecode . "&a=" . ($dates['1'] - 1) . "&b=" . $dates['2'] . "&c=" . $dates['0'] . "&d=" . ($dates['1'] - 1) . "&e=" . $dates['2'] . "&f=" . $dates['0'] . "&g=d&ignore=.csv";
				
				$filesize = 2000;
				$handle = @fopen($url, "r");
				if ($handle) {
					$raw_quote_data = fread($handle, $filesize);
					
					fclose($handle);
					
					$quote_array = explode("\n", $raw_quote_data);
					//pr($quote_array);
					array_shift($quote_array);
					array_pop($quote_array);
					
					$quote = explode(",", $quote_array['0']);
					return $quote['6'];
				}
				else
                return false;
			}
		}
		
		
		function admin_search_result($Code=null) {
			if (!empty($this->data) || !empty($Code)) {
				$this->loadModel("Director");
				$keyword = !empty($Code) ? $Code : trim($this->data['Codexec']['search_event']);
				$this->Director->recursive = 2;
				//$this->Director->unbindModel(array('hasMany' => array('Codtran')));
				$results = $this->Director->find('all', array("conditions" => array("Director.name like " => "%" . $keyword . "%"), "order" => array("Director.name" => "ASC")));
				//share price calculation
				$i = 0;
				foreach ($results as $rows) {
					$j=0;
					foreach ($rows['Codexec'] as $row) {
						
						switch ($row['Codetail']['Exch']) {
							case 'A': $Exch = ' ASX';$sharecode = $row['Codetail']['Code'] . ".AX";break;
							case 'N': $Exch = ' NSX';break;
							case 'B': $Exch = ' BSX';break;
							case 'Z': $Exch = ' NZX';$sharecode = $row['Codetail']['Code'] . ".NZ";break;
							case 'OZ': $Exch = ' Other AUS';break;
							case 'OA': $Exch = ' Other NZ';break;
							default: $Exch = "&nbsp;";
						}
						$results[$i]['Codexec'][$j]['AllShareChange'] = "&nbsp;";
						$results[$i]['Codexec'][$j]['AllShare'] = "&nbsp;";
						$results[$i]['Codexec'][$j]['current_price'] = "&nbsp;";
						$results[$i]['Codexec'][$j]['AppShare'] = "&nbsp;";
						$results[$i]['Codexec'][$j]['ResigShare'] = "&nbsp;";
						
						if ($row['App'] != "0000-00-00") {
							$results[$i]['Codexec'][$j]['AppShare'] = $this->sharequotes($sharecode, $row['App']);
							if ($results[$i]['Codexec'][$j]['AppShare']) {
								$current_price = "";
								if ($row['Resig'] != "0000-00-00") {
									$results[$i]['Codexec'][$j]['ResigShare'] = $this->sharequotes($sharecode, $row['Resig']);
									$current_price = $results[$i]['Codexec'][$j]['ResigShare'];
									} else {
									$results[$i]['Codexec'][$j]['current_price'] = $this->sharequotes($sharecode);
									$current_price = $results[$i]['Codexec'][$j]['current_price'];
								}
								if ($current_price != "") {
									$change = $current_price - $results[$i]['Codexec'][$j]['AppShare'];
									
									if ($change < 0)
									$results[$i]['Codexec'][$j]['AllShareChange'] = '<span style="color:red">' . round((($change * 100) / $results[$i]['Codexec'][$j]['AppShare']), 2) . "%</span>";
									else
									$results[$i]['Codexec'][$j]['AllShareChange'] = '<span style="color:green">' . round((($change * 100) / $results[$i]['Codexec'][$j]['AppShare']), 2) . "%</span>";
									
									if ($row['Resig'] != "0000-00-00") {
										$AllShare = $this->sharequotes("^AORD", $row['Resig']);
										if ($AllShare == "") {
											$timestamp = strtotime($row['Resig']) - (24 * 60 * 60);
											$AllShare = $this->sharequotes("^AORD", date("Y-m-d", $timestamp));
										}
										} else {
										$AllShare = $this->sharequotes("^AORD", $row['App']);
										if ($AllShare == "") {
											$timestamp = strtotime($row['App']) - (24 * 60 * 60);
											$AllShare = $this->sharequotes("^AORD", date("Y-m-d", $timestamp));
										}
									}
									$AllShare_current = $this->sharequotes("^AORD");
									$change1 = $AllShare_current - $AllShare;
									if ($change1 < 0)
									$results[$i]['Codexec'][$j]['AllShare'] = '<span style="color:red">' . round((($change1 * 100) / $AllShare), 1) . "%</span>";
									else
									$results[$i]['Codexec'][$j]['AllShare'] = '<span style="color:green">' . round((($change1 * 100) / $AllShare), 1) . "%</span>";
								}
							}
						}
						$j++;
					}
					$i++;
				}
				/*$this->Director->recursive = 2;
				$this->Director->unbindModel(array('hasMany' => array('Codexec')));
				$results_tran = $this->Director->find('all', array("conditions" => array("Director.name like " => "%" . $keyword . "%"), "order" => array("Director.name" => "ASC")));
				print_r($results_tran);*/
				//print_r($results);
				
				$this->loadModel('Codtran');				
				$this->Codtran->recursive=1;
				$codtrans = $this->Codtran->find("all", array("conditions" => array("Director.name like " => "%" . $keyword . "%"), "order" => array("Codtran.Date" => "DESC", "Codtran.Company" => "ASC")));
				
				$this->set('keyword', $keyword);
				$this->set('results', $results);
				$this->set('codtrans', $codtrans);
			}
		}
		
		function admin_add() {
			
			if (!empty($this->data)) {
				//pr($this->data);exit;
				
				if ($this->data['Codexec']['dir_title_id'] == "") {
					$this->data['Codexec']['dir_title_id'] = 0;
				}
				if ($this->data['Codexec']['dir_title_id2'] == "") {
					$this->data['Codexec']['dir_title_id2'] = 0;
				}
				if ($this->data['Codexec']['App']['day'] == "") {
					$this->data['Codexec']['App']['day'] = '00';
					$this->data['Codexec']['App']['year'] = '0000';
					$this->data['Codexec']['App']['month'] = '00';
				}
				if (isset($this->data['Codexec']['Resig']['day']) && $this->data['Codexec']['Resig']['day'] == "") {
					$this->data['Codexec']['Resig']['day'] = '00';
					$this->data['Codexec']['Resig']['year'] = '0000';
					$this->data['Codexec']['Resig']['month'] = '00';
				}
				if(isset($this->data['Codexec']['director_id'])){
					$this->Codexec->Director->recursive=-1;
					$dir=$this->Codexec->Director->findById($this->data['Codexec']['director_id']);
					$this->data['Codexec']['Name']=$dir['Director']['name'];
				}
				if(isset($this->data['Codexec']['Name'])){
					$this->loadModel("Director");
					$dir=$this->Director->findByName($this->data['Codexec']['Name']);
					if($dir['Director']['id']){
						$this->data['Codexec']['director_id']=$dir['Director']['id'];
						}else{
						$director['Director']['name']=$this->data['Codexec']['Name'];
						$this->Director->create();
						$this->Director->save($director);
						$this->data['Codexec']['director_id']=$this->Director->getLastInsertId();
					}
				}
				$this->Codexec->create();
				if ($this->Codexec->save($this->data)) {
					$this->Session->setFlash(__('The codexec has been saved', true));
					$this->redirect($_SERVER['HTTP_REFERER']);
					//$this->redirect(array('action' => 'index'));
					} else {
					$this->Session->setFlash(__('The codexec could not be saved. Please, try again.', true));
				}
			}
			$codetails = $this->Codexec->Codetail->find('list');
			$directors = $this->Codexec->Director->find('list');
			$titles = $this->Codexec->DirTitle->find('list');
			//pr($titles);
			$this->set(compact('codetails', 'titles', 'directors'));
		}
		
		function admin_edit($id = null) {
			if (!$id && empty($this->data)) {
				$this->Session->setFlash(__('Invalid codexec', true));
				$this->redirect(array('action' => 'index'));
			}
			//pr($this->data);
			if (!empty($this->data)) {
				if ($this->data['Codexec']['App']['day'] == "") {
					$this->data['Codexec']['App']['day'] = '00';
					$this->data['Codexec']['App']['year'] = '0000';
					$this->data['Codexec']['App']['month'] = '00';
				}
				if ($this->data['Codexec']['Resig']['day'] == "") {
					$this->data['Codexec']['Resig']['day'] = '00';
					$this->data['Codexec']['Resig']['year'] = '0000';
					$this->data['Codexec']['Resig']['month'] = '00';
				}
				if ($this->data['Codexec']['dir_title_id'] == "") {
					$this->data['Codexec']['dir_title_id'] = 0;
				}
				if ($this->data['Codexec']['dir_title_id2'] == "") {
					$this->data['Codexec']['dir_title_id2'] = 0;
				}
				
				$dir['Director']['name']=$this->data['Codexec']['Name'];
				$dir['Director']['id']=$this->data['Codexec']['director_id'];
				if ($this->Codexec->save($this->data)) {
					$this->Codexec->Director->save($dir);
					$this->Session->setFlash(__('The codexec has been updated', true));
					
					if (isset($_SERVER['HTTP_REFERER'])) {
						$this->redirect($_SERVER['HTTP_REFERER']);
					}
					//$this->redirect(array('action' => 'index'));
					} else {
					$this->Session->setFlash(__('The codexec could not be saved. Please, try again.', true));
				}
			}
			if (empty($this->data)) {
				$this->data = $this->Codexec->read(null, $id);
				//pr($this->data);
			}
			$codetails = $this->Codexec->Codetail->find('list');
			$titles = $this->Codexec->DirTitle->find('list');
			$directors = $this->Codexec->Director->find('list');
			$this->set(compact('codetails', 'titles', 'directors'));
		}
		
		function admin_delete($id = null) {
			if (!$id) {
				$this->Session->setFlash(__('Invalid id for codexec', true));
				$this->redirect(array('action' => 'index'));
			}
			if ($this->Codexec->delete($id)) {
				$this->Session->setFlash(__('Codexec deleted', true));
				if (isset($_SERVER['HTTP_REFERER'])) {
					$this->redirect($_SERVER['HTTP_REFERER']);
				}
				//$this->redirect(array('action'=>'index'));
			}
			$this->Session->setFlash(__('Codexec was not deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		
		function admin_export() {
			$this->Codexec->recursive = -1;
			// Find fields needed without recursing through associated models
			$codexecs = $this->Codexec->find(
			'all', array('order' => "Codexec.id ASC"));
			//pr($codetails);
			$this->layout = false;
			$this->autoLayout = false;
			$this->set('codexecs', $codexecs);
		}
		
		function admin_upload_csv() {
			if (!empty($this->data)) {
				//pr($this->data);
				if (!empty($this->data['Codexec']['fileName']['name']) && is_uploaded_file($this->data['Codexec']['fileName']['tmp_name'])) {
					if ($this->data['Codexec']['fileName']['type'] == "text/x-csv" OR $this->data['Codexec']['fileName']['type'] == "application/octet-stream" OR $this->data['Codexec']['fileName']['type'] == "application/vnd.ms-excel") {
						//$fileData = fread(fopen(, "r"),$this->data['Coevent']['fileName']['size']);
						$messages = $this->Codexec->import($this->data['Codexec']['fileName']['tmp_name']);
						//debug($messages);
						if (isset($messages['errors']) && count($messages['errors']) > 0) {
							$msg = implode("<br>", $messages['errors']);
							} else {
							$msg = implode("<br>", $messages['messages']);
						}
						//echo $msg;
						$this->Session->setFlash($msg);
						} else {
						$this->Session->setFlash(__('Invalid file type. You must upload a CSV file.', true));
					}
					} else {
					$this->Session->setFlash(__('CSV File Required.', true));
				}
			}
		}
		
	}
